package com.michael.demos.base.java.arithmetic;

/**
 * 类功能描述:
 * <pre>
 *   CPU高速缓存测试
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/04/26 08:25
 */
public class CpuCacheTest {

    public static void main(String[] args) {

        int arr[] = new int[64 * 1024 * 1024];

        long start = System.nanoTime();
        // 循环1
        for (int i = 0; i < arr.length; i++) {
            arr[i] *= 3;
        }
        long part1 = System.nanoTime();
        // 循环2
        for (int i = 0; i < arr.length; i += 16) {
            arr[i] *= 3;
        }
        long part2 = System.nanoTime();

        System.out.println(start);
        System.out.println(part1);
        System.out.println(part2);

        System.out.println(part1 - start);
        System.out.println(part2 - part1);

        // 循环2的耗费时间并不会比循环1的耗费时间低很多。

        System.out.println("$$$$$$$$$$$$$$$$$$");

        int[][] arr2 = new int[10000][10000];
        start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < 10000; j++) {
                arr2[i][j] *= 2;
            }
        }
        part1 = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < 10000; j++) {
                arr2[j][i] *= 2;
            }
        }
        part2 = System.nanoTime();
        System.out.println(start);
        System.out.println(part1);
        System.out.println(part2);

        System.out.println(part1 - start);
        System.out.println(part2 - part1);

        // 内存到CPU高速缓存是一小块一小块读取的，按列迭代使CPU高速缓存达不到相应的作用
    }
}
